﻿
Partial Class WebForm_MasterPage
    Inherits System.Web.UI.MasterPage

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Session("time") = System.DateTime.Now.ToString()
        Session.Timeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings("SessionTimeout"))
        'Me.lblTime.Value = Convert.ToString(Convert.ToInt32(Session.Timeout) * 60)

        If Me.Session("UserID") Is Nothing Then
            Response.Redirect("~\WebForm\Logout.aspx")
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Me.lblUserName.Text = clsAuth.GetUserID() & "(" & HttpUtility.UrlDecode(Request.Cookies("UserName_" + UserName).Value) & ")"
        Me.lblUserName.Text = clsAuth.GetUserID() & "(" & clsCookie.CookieGet("UserName") & ")"
        Me.lblDate.Text = DateTime.Today.ToLongDateString
        'Me.lblOrganizationName.Text = "所屬單位：" & clsAuth.GetOrganizationName(clsAuth.GetUserID)
        If Not IsPostBack Then

            If Me.CheckAuth() = True Then
                Me.FixAjaxBug()
                Me.BindData()
                Me.AuthPage()

            Else
                MyObj.ShowMessage(Me.GetLocalResourceObject("CheckAuth_Failure"))
            End If

        End If
    End Sub

    Protected Sub lbtnLogout_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbtnLogout.Click
        Response.Redirect("~\WebForm\Logout.aspx")
    End Sub
End Class

Partial Class WebForm_MasterPage
    Private Sub AuthPage()

  
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Dim dt As New Data.DataTable
        Dim pt As New Data.DataTable
        Dim NowUrl As String = Request.Url.PathAndQuery.Substring(Request.Url.PathAndQuery.Split("/").Length, Request.Url.PathAndQuery.Length - Request.Url.PathAndQuery.Split("/").Length).Replace("/", "\")

        sql.Length = 0
        sql.AppendFormat("Select substring(url,2,len(url)) as Url from Program  ")
        sql.AppendFormat("where 1=1 and substring(url,2,len(url))='{0}' ", NowUrl)
        pt = dat.GetData(sql)

        If pt.Rows.Count > 0 Then
            sql.Length = 0
            sql.AppendFormat("select  distinct substring(url,2,len(url)) as Url from  Program p  ")
            sql.AppendFormat("inner join RoleProgramMapping rpm   on p.ProgramID=rpm.ProgramID ")
            sql.AppendFormat("and rpm.RoleID in ( select * from fn_GetAllRoleIDByUserID('{0}') ) ", clsAuth.GetUserID())
            sql.AppendFormat("where 1=1 and substring(url,2,len(url))='{0}' ", NowUrl)

            dt = dat.GetData(sql)
            If dt.Rows.Count = 0 Then
                Response.Redirect("~/WebForm/NoPermission.aspx")
            Else
                Return
            End If
        End If

    End Sub
    Private Function CheckAuth() As Boolean
        Dim dat As New clsData
        Dim sql As New MyStringBuilder
        Dim dt As New Data.DataTable

        '檢查此表單是否需控管
        sql.Length = 0
        sql.AppendFormat("select p.* from ProtectedProgram p ")
        sql.AppendFormat("where p.Url = '{0}' ", clsAuth.GetUserID())

        dt = dat.GetData(sql)

        If dt.Rows.Count = 0 Then
            '不需控管，直接跳過檢查
            Return True
        End If

        sql.Length = 0
        sql.AppendFormat("select pa.* from UserProgramAuth pa ")
        sql.AppendFormat("inner join ProtectedProgram p on pa.ProgramID = p.ProgramID ")
        sql.AppendFormat("where p.Active = 'Y' ")
        sql.AppendFormat("and p.Url = '{0}' ", clsAuth.GetProgramUrl())
        sql.AppendFormat("and pa.UserID = '{0}' ", clsAuth.GetUserID())

        dt = dat.GetData(sql)

        If dt.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If

    End Function

    Private Sub FixAjaxBug()
        'CalendarExtendar with MultiView + UpdatePanel bug
        'http://dotnetrush.blogspot.com/2008/02/ajax-calendarextender-bug-fixes.html

        Dim url As String = Page.ClientScript.GetWebResourceUrl(GetType(AjaxControlToolkit.ClientCssResourceAttribute), "AjaxControlToolkit.Calendar.Calendar.css")
        Dim myHtmlLink As New HtmlLink()
        myHtmlLink.Href = url
        myHtmlLink.Attributes.Add("rel", "stylesheet")
        myHtmlLink.Attributes.Add("type", "text/css")
        Page.Header.Controls.Add(myHtmlLink)
    End Sub

    Private Sub BindSiteMap()
        'Me.SiteMapPath1.currentno()
    End Sub

    Private Sub BindData()
        'Me.btnLogout.Text = String.Format("{0} {1}", Request.Cookies("UserName").Value, Me.GetLocalResourceObject("btnLogout.Text"))
    End Sub

    Public ReadOnly Property SiteMapPath() As SiteMapPath
        Get
            Return Me.SiteMapPath1
        End Get
    End Property


#Region "Action Lock"
    ''' <summary>
    ''' 因為每次PostBack後SessionID會不一樣所以自製一定SessionID
    ''' </summary>
    ''' <value></value>
    ''' <returns> 因為每次PostBack後SessionID會不一樣所以自製一定SessionID</returns>
    ''' <remarks> 因為每次PostBack後SessionID會不一樣所以自製一定SessionID</remarks>
    Public Property mySessionID() As String
        Get
            If Session("SessionID") Is Nothing Then
                Session("SessionID") = Session.SessionID
            End If
            Return Session("SessionID")
        End Get
        Set(ByVal value As String)
            Session("SessionID") = value
        End Set
    End Property

    ''' <summary>
    ''' 檢查是否已經輪到這個SessionID,如果尚在排隊則會繼續排隊,最多會等10分
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub checkLock()
        Dim serverDB As SYS.DAO.sysServerDAO = New SYS.DAO.sysServerDAO()
        For ii As Integer = 0 To 600
            If serverDB.CheckLock(Request.ServerVariables("Local_addr"), mySessionID) Then
                System.Threading.Thread.Sleep(1000)
            Else
                Exit For
            End If
        Next
    End Sub

    ''' <summary>
    ''' 頁面開啟時將檢查是否已輪到自己的SessionID
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks>頁面開啟時將檢查是否已輪到自己的SessionID</remarks>
    Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
        '先Lock順序
        Dim serverDB As SYS.DAO.sysServerDAO = New SYS.DAO.sysServerDAO()
        serverDB.TryLock(Request.ServerVariables("Local_addr"), mySessionID)
        checkLock()

        MyBase.OnLoad(e)
    End Sub

    ''' <summary>
    ''' 頁面結束時將Lock的資料刪除
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks>頁面結束時將Lock的資料刪除</remarks>
    Protected Overrides Sub OnUnload(ByVal e As System.EventArgs)
        ''解開順序的資料
        Dim serverDB As SYS.DAO.sysServerDAO = New SYS.DAO.sysServerDAO()
        serverDB.unLock(mySessionID)
        MyBase.OnUnload(e)
    End Sub

    ''' <summary>
    ''' 處理程式沒有攔到錯誤的地方,不要秀出原始檔等相關的頁面出來
    ''' </summary>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Overrides Sub OnError(ByVal e As System.EventArgs)
        '解開順序的資料
        Dim serverDB As SYS.DAO.sysServerDAO = New SYS.DAO.sysServerDAO()
        serverDB.unLock(mySessionID)

        Server.ClearError()
        MyBase.OnError(e)
    End Sub

#End Region
End Class


